package com.jay.tools.utils.file_util;

import android.content.Context;
import android.content.res.AssetManager;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class AssetUtils {
    /**
     * 复制assets文件到 指定目录
     *
     * @param context
     * @param assetsName 要复制的assets文件名
     * @param savePath   保存路径
     * @param saveName   保存名称
     */
    public static File loadAsset2File(Context context, String assetsName, String savePath, String saveName) {
        try {
            String filePath = savePath + "/" + saveName;
            File dir = new File(savePath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(filePath);

            if (!file.exists()) {
                InputStream is = context.getResources().getAssets().open(assetsName);
                FileOutputStream fos = new FileOutputStream(filePath);
                byte[] buffer = new byte[2048];
                int count = 0;
                while ((count = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                }
                fos.close();
                is.close();
                return file;
            } else {
                return file;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String loadAsset2Str(Context context, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

}
